from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models
from .serializer import *

#登录
class LoginView(APIView):
    def post(self,request):
        name=request.data.get('name','').strip()
        authobj=models.Author.objects.filter(name=name).first()

        if authobj:
            return Response({'code':1000,'msg':'登录成功','data':authobj.id})
        return Response({'code': 1001, 'msg': '用户名错误'})


# 图书
class BookView(APIView):
    def get(self,request):
        bookquery=models.Books.objects.filter(id=id).all()
        obj=BookSerializer(bookquery,many=True)
        return Response({'code':1000,'msg':'','data':obj.data})




    def post(self,request):
        name=request.POST.get('name','').strip()
        price = request.POST.get('price','').strip()
        desc = request.POST.get('desc', '').strip()
        uid = request.POST.get('uid', 0)
        img = request.FILES.get('img')

        data={
            'name':name,
            'price':price,
            'desc':desc,
            'author_id':uid,
            'img':img
        }

        obj=BookUnserializer(data=data)

        if obj.is_valid():
            flag=obj.save()
            if flag:
                return Response({'code':1000,'mag':'添加成功'})
            return Response({'code':1001,'mag':'添加失败'})

        print(obj.errors)
        return Response({'code': 1002, 'mag': '参数有误'})



    def delete(self,request):
        id=request.data.get('id')
        booktupele=models.Books.objects.filter(id=id).delete()
        if booktupele[0]:
            return Response({'code':1000,'msg':'删除成功'})
        return Response({'code': 1000, 'msg': '删除失败'})
